package cn.wolfcode.rbac.service.impl;

import cn.wolfcode.rbac.domain.Department;
import cn.wolfcode.rbac.ex.BusinessException;
import cn.wolfcode.rbac.mapper.DepartmentMapper;
import cn.wolfcode.rbac.query.QueryObject;
import cn.wolfcode.rbac.service.IDepartmentService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class DepartmentServiceImpl implements IDepartmentService {
    @Autowired
    private DepartmentMapper departmentMapper;

    public int deleteByPrimaryKey(Long id) {
        return departmentMapper.deleteByPrimaryKey(id);
    }

    public int insert(Department dept) {
        return departmentMapper.insert(dept);
    }

    public Department selectByPrimaryKey(Long id) {
        return departmentMapper.selectByPrimaryKey(id);
    }

    public List<Department> selectAll() {
        return departmentMapper.selectAll();
    }

    @Override
    public PageInfo<Department> selectList(QueryObject qo) {
        // 1 启动分页插件
        PageHelper.startPage(qo.getPageNum(),qo.getPageSize());
        // 2 调用查询列表的SQL语句，得到分页的list ，封装到PageInfo对象上
        List<Department> list = departmentMapper.selectAll();
        return new PageInfo<Department>(list);
    }

    public int updateByPrimaryKey(Department dept) {
        return departmentMapper.updateByPrimaryKey(dept);
    }

    @Override
    public void saveOrUpdate(Department department) {
        if(department.getId()==null){
            //属于新增操作
            departmentMapper.insert(department);
        }else{
            //数据编辑操作
            departmentMapper.updateByPrimaryKey(department);
        }
    }

    @Override
    public void update(Long id, Department department) {
        if(id==null){
            throw new BusinessException("非法操作");
        }
        /*Department dept = departmentMapper.selectByPrimaryKey(id);
        if(dept==null){
            throw new BusinessException("非法操作");
        }*/
        department.setId(id);
        int count = departmentMapper.updateByPrimaryKey(department);
        if(count==0){
            throw new BusinessException("修改失败");
        }
    }
}
